package com.btex.app;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.btex.app.entity.Identity;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.LogUtil;
import com.btex.app.tools.MicroAVLIDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class ConfirmIdentityActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {

    private static final java.lang.String TAG = "ConfirmIdentityActivity";
    private Spinner spinner;
    private EditText etIDCard, etTrueName;
    private Button btnConfirm;
    private String type = "1"; //1身份证3护照
    private PreferencesCookieStore cookieStore;
    private ArrayAdapter<String> adapter;
    private List<Identity> identities = new ArrayList<>();
    private List<String> des = new ArrayList<>();
    private MicroAVLIDialog mMicroAVLIDialog;

    private void assignViews() {
        spinner = (Spinner) findViewById(R.id.spinner);
        etIDCard = (EditText) findViewById(R.id.etIDCard);
        etTrueName = (EditText) findViewById(R.id.etTrueName);
        btnConfirm = (Button) findViewById(R.id.btnConfirm);
        btnConfirm.setOnClickListener(this);
        spinner.setOnItemSelectedListener(this);
        etTrueName.addTextChangedListener(new MyWatcher());
        etIDCard.addTextChangedListener(new MyWatcher());
        getIdentity();

        initData();
    }

    private void getIdentity() {

        OkGo.<String>get(Config.URL_APP_CONFIG).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();
                LogUtil.i(TAG, "result:" + result);
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    LogUtil.i(TAG, "KEY_CODE:" + jsonObj.getString(Config.KEY_CODE));
                    if ("1".equals(jsonObj.getString(Config.KEY_CODE))) {
                        Gson gson = new Gson();
                        JSONArray date = jsonObj.getJSONArray(Config.KEY_DATA);
                        LogUtil.i(TAG, "data:" + date);
                        String opts = date.getString(0);
                        jsonObj = new JSONObject(opts);

                        Type listType = new TypeToken<ArrayList<Identity>>() {
                        }.getType();
                        LogUtil.i(TAG, "opts:" + opts);
                        identities = gson.fromJson(jsonObj.getString("opts"), listType);

                        if (identities != null) {
                            for (int i = 0; i < identities.size(); i++) {
                                des.add(identities.get(i).getDesc());
                            }
                        }
                        LogUtil.i(TAG, "identities:" + identities.toString());
                        String[] m = des.toArray(new String[des.size()]);
                        LogUtil.i(TAG, "m:" + m);
                        //将可选内容与ArrayAdapter连接起来
                        adapter = new ArrayAdapter<String>(cxt, android.R.layout.simple_spinner_item, m);

                        //设置下拉列表的风格
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                        //将adapter 添加到spinner中
                        spinner.setAdapter(adapter);
                    }
                } catch (Exception e) {
                    LogUtil.e(TAG, e.toString());
                }
            }
        });


//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.URL_APP_CONFIG, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                String result = responseInfo.result.toString();
//                LogUtil.i(TAG, "result:" + result);
//                try {
//                    JSONObject jsonObj = new JSONObject(result);
//                    LogUtil.i(TAG, "KEY_CODE:" + jsonObj.getString(Config.KEY_CODE));
//                    if ("1".equals(jsonObj.getString(Config.KEY_CODE))) {
//                        Gson gson = new Gson();
//                        JSONArray date = jsonObj.getJSONArray(Config.KEY_DATA);
//                        LogUtil.i(TAG, "data:" + date);
//                        String opts = date.getString(0);
//                        jsonObj = new JSONObject(opts);
//
//                        Type listType = new TypeToken<ArrayList<Identity>>() {
//                        }.getType();
//                        LogUtil.i(TAG, "opts:" + opts);
//                        identities = gson.fromJson(jsonObj.getString("opts"), listType);
//
//                        if (identities != null) {
//                            for (int i = 0; i < identities.size(); i++) {
//                                des.add(identities.get(i).getDesc());
//                            }
//                        }
//                        LogUtil.i(TAG, "identities:" + identities.toString());
//                        String[] m = des.toArray(new String[des.size()]);
//                        LogUtil.i(TAG, "m:" + m);
//                        //将可选内容与ArrayAdapter连接起来
//                        adapter = new ArrayAdapter<String>(cxt, android.R.layout.simple_spinner_item, m);
//
//                        //设置下拉列表的风格
//                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//
//                        //将adapter 添加到spinner中
//                        spinner.setAdapter(adapter);
//                    }
//                } catch (Exception e) {
//                    LogUtil.e(TAG, e.toString());
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//                Toast.makeText(cxt, getString(R.string.net_erro), Toast.LENGTH_SHORT).show();
//            }
//        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_identity);
        assignViews();
        mMicroAVLIDialog = new MicroAVLIDialog(this);
        cookieStore = CookieTool.getCookieStore(cxt, sp);
    }


    @Override
    public void setData() {
        tv_title.setText(getString(R.string.regist_identity));


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btnConfirm:
                mMicroAVLIDialog.show();
                String iDCard = etIDCard.getText().toString();
                confirmChange(type, iDCard, etTrueName.getText().toString());
                break;

            default:
                break;
        }
    }

    /**
     * 确认修改密码
     */
    private void confirmChange(String type, String iDCard, String trueName) {


        String isEngilshs;

        boolean isEngilsh = sp.getBoolean("isEngilsh", false);
        if (isEngilsh) {
            isEngilshs = "en";
        } else {
            isEngilshs = "zh_cn";
        }


        RequestParams params = new RequestParams();
        params.addBodyParameter("type", type);
        params.addBodyParameter("no", iDCard);
        params.addBodyParameter("true_name", trueName);
        params.addBodyParameter("lang", isEngilshs);

        OkGo.<String>post(Config.URL_SET_IDCARD).params("type", type).params("no", iDCard).params("true_name", trueName).params("lang", isEngilshs).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                mMicroAVLIDialog.dismiss();
                String result = response.body();
                LogUtil.i(TAG, "result:" + result);
                Log.i("kqjwndkqjwndq23kw", result);
                try {
                    JSONObject json = new JSONObject(result);
                    if ("1".equals(json.getString(Config.KEY_CODE))) {
//                        new SendPushInfo(sp.getString("baiduID", null), cxt, "baidu");
//                        new SendPushInfo(sp.getString("xiaomiID", null), cxt, "xiaomi");
                        sp.putBoolean(Config.KEY_IS_LOGIN, true);    //此时已登陆
                        sp.putString("check", "0");
                        EventBus.getDefault().post("killActivity");
                        startActivity(new Intent(cxt, TabsActivity.class));
                        finish();
                    } else if ("-1".equals(json.getString(Config.KEY_CODE))) {
                        Toast.makeText(cxt, json.getString("info"), Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    LogUtil.i(TAG, e.toString());
                }
            }
        });

//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.URL_SET_IDCARD, params, new RequestCallBack<Object>() {
//            @Override
//            public void onSuccess(ResponseInfo<Object> responseInfo) {
//                mMicroAVLIDialog.dismiss();
//                String result = responseInfo.result.toString();
//                LogUtil.i(TAG, "result:" + result);
//                Log.i("kqjwndkqjwndq23kw", result);
//                try {
//                    JSONObject json = new JSONObject(result);
//                    if ("1".equals(json.getString(Config.KEY_CODE))) {
////                        new SendPushInfo(sp.getString("baiduID", null), cxt, "baidu");
////                        new SendPushInfo(sp.getString("xiaomiID", null), cxt, "xiaomi");
//                        sp.putBoolean(Config.KEY_IS_LOGIN, true);    //此时已登陆
//                        sp.putString("check", "0");
//                        EventBus.getDefault().post("killActivity");
//                        startActivity(new Intent(cxt, TabsActivity.class));
//                        finish();
//                    } else if ("-1".equals(json.getString(Config.KEY_CODE))) {
//                        Toast.makeText(cxt, json.getString("info"), Toast.LENGTH_SHORT).show();
//                    }
//
//                } catch (JSONException e) {
//                    LogUtil.i(TAG, e.toString());
//                }
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//                Toast.makeText(cxt, msg, Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        type = identities.get(position).getValue();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            if (!TextUtils.isEmpty(etIDCard.getText()) && !TextUtils.isEmpty(etTrueName.getText())) {
                btnConfirm.setBackgroundResource(R.drawable.selector_btn_app_color);
                btnConfirm.setClickable(true);
                btnConfirm.setTextColor(getResources().getColor(R.color.white));
            } else {
                btnConfirm.setBackgroundResource(R.color.bg_gray);
                btnConfirm.setClickable(false);
                btnConfirm.setTextColor(getResources().getColor(R.color.tv_gray));
            }
        }
    }

}
